package com.spring.demo.core.aop;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component("controllerAspect")
public class ControllerAspect {

	@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
	public void requestMappingMethod() {
	}

	@Pointcut("within(@org.springframework.stereotype.Controller *)")
	public void controllerClass() {
	}

	@Before("requestMappingMethod() && controllerClass()")
	public void beforeAdvice(JoinPoint joinPoint) throws Throwable {
		System.out.println("Invoke " + niceName(joinPoint));
	}

	@AfterReturning("requestMappingMethod() && controllerClass()")
	public void afterReturningAdvice(JoinPoint joinPoint) {
		System.out.println("Finished: " + niceName(joinPoint));
	}

	private String niceName(JoinPoint joinPoint) {
		return joinPoint.getTarget().getClass() + "#"
				+ joinPoint.getSignature().getName() + "\n\targs "
				+ Arrays.toString(joinPoint.getArgs());
	}

}
